#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/** Autuor : zhaoshun
  * Time   : 2017/12/03 21:05
  * Email  : tmby1314@163.com
  * student ID: 716101010107
  * */


int main_pipe(int argc, char const *argv[]) {

    if (NULL == argv[1] || NULL == argv[2]) {
        printf("Usage : copy file1 file1");
        exit(10);
    }

    char const * src_file = argv[1];
    char const * dest_file = argv[2];
    char * name_pipe = "iofile";

    const int size = 1024;
    int sfd,dfd,sp,dp;
    char buff[size];
    sfd = open(src_file,O_RDONLY,0644);
    dfd =open(dest_file,O_WRONLY|O_CREAT|O_TRUNC,0644);
    mknod(name_pipe,S_IFIFO|0666,0);
    ssize_t  n;

    if(fork()) {
        sp=open(name_pipe,O_WRONLY);
        while((n=read(sfd,buff,size))>0)
            write(sp,buff,n);
        close(sp);
        close(sfd);
    }  else {
        dp=open("iofile",O_RDONLY|O_NDELAY);
        while((n= read(dp,buff,size))!=1)
            if(n==0)
                sleep(5);
            else write(dfd,buff,strlen(buff));
        close(dp);
        close(dfd);
    }
    return 0;

}